package com.jackrain.nea.fc.dl.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.common.*;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.dl.common.utils.esutil.ConvertQueryListUtil;
import com.jackrain.nea.dl.common.utils.esutil.ElasticsearchUtil;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.dl.api.ViewDLTranPlanSaveCmd;
import com.jackrain.nea.fc.dl.mapper.ViewDLTranPlanMapper;
import com.jackrain.nea.fc.utils.Constants;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySessionImpl;
import com.jackrain.nea.web.security.Security4Utils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * 调拨计划单 F4->中间表->FC
 *
 * @author wuwenxue
 * @date 2018/05/11
 **/
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "cp")
public class ViewDLTranPlanSaveCmdImpl extends CommandAdapter implements ViewDLTranPlanSaveCmd {

    @Autowired
    PostHandleEvent postHandleEvent;

    @Autowired
    PostDubbleEvent postDubbleEvent;

    @Autowired
    private ElasticsearchUtil esUtil;

    @Autowired
    private ConvertQueryListUtil convertQLUtil;

    @Autowired
    private BtranEsName btranEsName;

    @Autowired
    RestTemplateUtil restTemplateUtil;

    @Autowired
    private PropertiesConf pconf;

    private Logger accesLogger = LoggerFactory.getLogger(Constants.ACCESS_PARAM_LOGGER);

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {

        ValueHolder vh = new ValueHolder();
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"),
                "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        log.info("ViewDLTranPlanSaveCmdImpl--param-->{}",param);

        ViewDLTranPlanMapper viewDLTranPlanMapper = ApplicationContextHandle.getBean(ViewDLTranPlanMapper.class);

        if (null == param || param.size() == 0) {
            throw new NDSException("参数格式错误！");
        }

        JSONArray paramArray = param.getJSONArray("data");
        JSONArray spendTimeArray = new JSONArray();
        JSONArray queryDataArray = new JSONArray();
        JSONArray errorArray = new JSONArray();
        JSONArray successIds = new JSONArray();
        for (int i = 0; i < paramArray.size(); i++) {
            JSONObject errorJson = new JSONObject();
            JSONObject retSucc = new JSONObject();
            JSONObject tranJson = paramArray.getJSONObject(i);
            JSONObject zbJS = tranJson.getJSONObject("DL_T_SQ_TRANSFER");
            JSONArray itemJS = tranJson.getJSONArray("DL_T_SQ_ITEM_TRANSFER");
            try {
                JSONObject spendTime = new JSONObject();
                Long retObjid = null;
                Long fc_id = zbJS.getLong("TRAN_PLAN_ID");
                String userName = zbJS.getString("OPR_ECODE");
                String idList = zbJS.getString("IDLIST");
                String bill_No = zbJS.getString("BILL_NO");
                String statusType = zbJS.getString("STATUS_TYPE");


                String field = "ID";
                JSONObject whereJS = new JSONObject();
                whereJS.put("BILL_NO", bill_No);

                HashMap isExist = QueryDLUtil.queryDL("DL_B_TRAN_PLAN", field, whereJS);
                if (null != isExist && isExist.size() > 0) {
                    retObjid = TypeUtils.castToLong(isExist.get("ID"));
                }

                //已提交 && 正常新增
                if ("CHECK".equals(statusType) && null != retObjid && retObjid > 0) {
                    retSucc.put("succIdList", idList);
                    retSucc.put("retObjid", retObjid);
                    successIds.add(retSucc);
                    continue;
                }

//                //es查询
//                JSONObject jsonObject = es(bill_No);
//                List<Long> longs = convertQLUtil.selectId(jsonObject.toString());
//                if (null != longs && longs.size() > 0) {
//                    retObjid = longs.get(0);
//                    JSONObject source = billdata(jsonObject);
//                    Integer status = source.getInteger("STATUS");
//
//                    //已提交 && 正常新增
//                    if ("CHECK".equals(statusType)) {
//                        retSucc.put("succIdList", idList);
//                        retSucc.put("retObjid", retObjid);
//                        successIds.add(retSucc);
//                        continue;
//                    }
//                }

                //用户
                if (null == userName) {
                    userName = "root";
                }
                User user = Security4Utils.getUser(userName);

                if (null == fc_id || fc_id <= 0) {
                    fc_id = retObjid;
                }

//                log.debug("==============================" + fc_id);
                int size = itemJS.size();
                if ("BILL_RATION_EXEC".equals(statusType)) {
                    if (null == fc_id || fc_id <= 0) {
                        throw new NDSException("ID为空，或未查询到该调拨单！");
                    }
                    long execStartTime = System.currentTimeMillis();
                    String notic = "com.jackrain.nea.dl.tran.api.BtranplanMultiExecutorCmd:1.0:dl";
                    QuerySessionImpl querySession = new QuerySessionImpl(user);
                    DefaultWebEvent event = new DefaultWebEvent("dlTranPlan", new HashMap(16));

                    JSONObject execJson = dealTranPlan(tranJson, viewDLTranPlanMapper, user, statusType);
                    execJson.put("Id", fc_id);
//                    log.info("----BILL_RATION_EXEC--->" + execJson);
                    event.put("param", execJson);
                    accesLogger.info("ViewDLTranPlanSaveCmdImpl--execJson-->{}",execJson);

                    querySession.setEvent(event);

                    if (size > 2000) {
                        asyncSave(execJson, querySession, event, idList, "BILL_RATION_EXEC");
                    } else {
                        JSONObject retJo = postDubbleEvent.executePostDubble(notic, querySession);
                        accesLogger.info("ViewDLTranPlanSaveCmdImpl--retJo-->{}",retJo);

                        double execEndTime = (double) (System.currentTimeMillis() - execStartTime) / 1000.0D;
                        spendTime.put("execTime->", execEndTime);
                        spendTime.put("tranplanBillRationExecRetData->", retJo);
//                        log.info("执行retData-->" + retJo);
                        if (!retJo.containsKey("code")){
                            throw new NDSException("执行返回值有误！无code");
                        }
                        if ((int) retJo.get("code") != 0) {
                            errorJson.put("key", idList);
                            if (null == retJo.get("message")) {
                                errorJson.put("message", "调拨计划单执行操作服务调用异常");
                            } else {
                                errorJson.put("message", "调拨计划单执行操作->" + retJo.get("message") +
                                        " error->" + retJo.get("error"));
                            }
                            errorArray.add(errorJson);
                            continue;
                        }
                    }
                    queryDataArray.add(execJson);
                }
                if ("BILL_RATION_CHANGE".equals(statusType)) {
                    if (null == fc_id || fc_id <= 0) {
                        throw new NDSException("ID为空，或未查询到该调拨单！");
                    }
                    long changeStartTime = System.currentTimeMillis();
                    String notic = "com.jackrain.nea.dl.tran.api.BtranplanChangeVirtualStoreCmd:1.0:dl";
                    JSONObject execJson = dealTranPlan(tranJson, viewDLTranPlanMapper, user, statusType);
                    execJson.put("Id", fc_id);

                    QuerySessionImpl querySession = new QuerySessionImpl(user);
                    DefaultWebEvent event = new DefaultWebEvent("dlTranPlan", new HashMap(16));
                    event.put("param", execJson);
                    querySession.setEvent(event);

                    if (size > 2000) {
                        asyncSave(execJson, querySession, event, idList, "BILL_RATION_CHANGE");
                    } else {
                        JSONObject retJo = postDubbleEvent.executePostDubble(notic, querySession);
                        double changeEndTime = (double) (System.currentTimeMillis() - changeStartTime) / 1000.0D;
                        spendTime.put("changeTime->", changeEndTime);
                        spendTime.put("tranplanBillRationChangeRetData->", retJo);
//                        log.info("换店retData-->" + retJo);
                        if (!retJo.containsKey("code")){
                            throw new NDSException("换店返回值有误！无code");
                        }
                        if (retJo.containsKey("code") && (int) retJo.get("code") != 0) {
                            errorJson.put("key", idList);
                            if (null == retJo.get("message")) {
                                errorJson.put("message", "调拨计划单换店操作服务调用异常");
                            } else {
                                errorJson.put("message", "调拨计划单换店操作->" + retJo.get("message") +
                                        " error->" + retJo.get("error"));
                            }
                            errorArray.add(errorJson);
                            continue;
                        }
                    }
                    queryDataArray.add(execJson);
                }
                if ("CHECK".equals(statusType)) {
                    long saveStartTime = System.currentTimeMillis();
                    String noticSav = "com.jackrain.nea.dl.tran.api.BtranplanBufferSaveCmd:1.0:dl";
                    JSONObject resultJson = dealTranPlan(tranJson, viewDLTranPlanMapper, user, statusType);
//                    log.info("----保存操作-----");
                    QuerySessionImpl querySession = new QuerySessionImpl(user);
                    DefaultWebEvent event = new DefaultWebEvent("dlTranPlan", new HashMap(16));
                    event.put("command", noticSav);
                    event.put("table", "DL_B_TRAN_PLAN");
                    event.setParameter("isSendMq", "N");
                    event.put("param", resultJson);
                    querySession.setEvent(event);

                    //调用调拨计划单保存程序
                    if (size > 2000) {
                        asyncSave(resultJson, querySession, event, idList, "CHECK");
                    } else {
                        JSONObject retSavJo = postHandleEvent.executePostHandle(resultJson, querySession, event, "save");
                        double saveEndTime = (double) (System.currentTimeMillis() - saveStartTime) / 1000.0D;
                        spendTime.put("saveTime->", saveEndTime);
                        spendTime.put("tranplanSaveRetData->", retSavJo);
                        log.info("SaveRetData-->" + retSavJo);
                        if (!retSavJo.containsKey("code")){
                            throw new NDSException("保存返回值有误！无code");
                        }
                        if ((int) retSavJo.get("code") != 0) {
                            errorJson.put("key", idList);
                            if (null == retSavJo.get("message")) {
                                errorJson.put("message", "调拨计划单保存标准服务调用异常");
                            } else {
                                errorJson.put("message", "调拨计划单保存异常->" + retSavJo.get("message"));
                            }
                            errorArray.add(errorJson);
                            continue;
                        }
                        JSONObject retData = retSavJo.getJSONObject("data");
                        retObjid = retData.getLong("objid");
                    }
                    queryDataArray.add(resultJson);
                }
                retSucc.put("retObjid", retObjid);
                retSucc.put("succIdList", idList);
                successIds.add(retSucc);
                spendTimeArray.add(spendTime);
            } catch (Exception e) {
                String error = "";
                if ((e instanceof NDSException)) {
                    error = e.getMessage();
                } else {
                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    e.printStackTrace(pw);
                    error = sw.toString();
                }
                String idList = zbJS.getString("IDLIST");
                errorJson.put("key", idList);
                errorJson.put("message", error);
                errorArray.add(errorJson);
            }
        }

        if (errorArray.size() > 0) {
            vh.put("error", errorArray);
            vh.put("code", -1);
        } else {
            vh.put("code", 0);
        }
        vh.put("queryDataArray", queryDataArray);
        vh.put("successIds", successIds);
        vh.put("spendTime", spendTimeArray);
        return vh;
    }

    @Async
    public void asyncSave(JSONObject resultJson, QuerySessionImpl querySession, DefaultWebEvent event,
                          String idList, String type) throws Exception {
        JSONObject retJson = null;
        String action = "";
        if ("BILL_RATION_EXEC".equals(type)) {
            action = "执行";
            String notic = "com.jackrain.nea.dl.tran.api.BtranplanMultiExecutorCmd:1.0:dl";
            retJson = postDubbleEvent.executePostDubble(notic, querySession);
        } else if ("BILL_RATION_CHANGE".equals(type)) {
            action = "换店";
            String notic = "com.jackrain.nea.dl.tran.api.BtranplanChangeVirtualStoreCmd:1.0:dl";
            retJson = postDubbleEvent.executePostDubble(notic, querySession);
        } else if ("CHECK".equals(type)) {
            action = "保存";
            retJson = postHandleEvent.executePostHandle(resultJson, querySession, event, "save");
        }
        log.info(action + "-->asyncRetData-->" + retJson);
        String flag = "";
        String message = "";
        if (retJson.containsKey("code") && (int) retJson.get("code") != 0) {
            flag = "false";
            if (null == retJson.get("message")) {
                message = "调拨计划单" + action + "标准服务调用异常";
            } else {
                message = "调拨计划单" + action + "异常->" + retJson.get("message");
            }
        } else {
            flag = "succ";
        }

        String fccloudUrl = pconf.getProperty("fccloud.url", "");
        URI uri = new URI(fccloudUrl + "/fccloud.write.billout");
        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();

        JSONObject paramObject = new JSONObject();
        paramObject.put("IDLIST", idList);
        paramObject.put("flag", flag);
        paramObject.put("message", message);
        paramObject.put("tableName", "DL_T_TRAN_TRANSFER");

        map.add("param", paramObject.toJSONString());
        restTemplateUtil.doPostForm(uri, map);
    }


    public JSONObject dealTranPlan(JSONObject tranJson, ViewDLTranPlanMapper viewDLTranPlanMapper, User user, String statusType) {

        JSONObject zbJS = tranJson.getJSONObject("DL_T_SQ_TRANSFER");
        JSONArray itemJS = tranJson.getJSONArray("DL_T_SQ_ITEM_TRANSFER");
        JSONArray tranPlanItemArray = new JSONArray();
        //明细款
        StringBuffer ecodeList = new StringBuffer();
        //明细款名称
        StringBuffer enameList = new StringBuffer();
        //品类ID集合
        StringBuffer departIdBuffer = new StringBuffer();
        //计划执行数量合计
        BigDecimal qtyExecPlan = BigDecimal.ZERO;
        //调拨金额合计
        BigDecimal amtExec = BigDecimal.ZERO;
        //已执行数量合计
        BigDecimal qtyExec = BigDecimal.ZERO;
        //未执行数量合计
        BigDecimal qtyExecPre = BigDecimal.ZERO;
        //门店数量
//        Integer qtyStore = 0;
        //未执行门店数
//        Integer storeExecPre = 0;

        List<String> proEcodeList = new ArrayList();
        List<Long> departIdList = new ArrayList();
        Long storeID = null;

        /*************处理明细表数据************/
        for (int j = 0; j < itemJS.size(); j++) {
            JSONObject itemJson = itemJS.getJSONObject(j);
            itemJson.put("ID", -1);
            itemJson.put("ISACTIVE", "Y");

            //商品ID
            if (null != itemJson.getString("PS_C_SKU_ECODE")) {
                String skuEcode = itemJson.getString("PS_C_SKU_ECODE");
                HashMap h = viewDLTranPlanMapper.selSkuData(skuEcode);

                if (null != h) {
                    if (null != h.get("PS_C_SPEC1OBJ_ID")) {
                        //颜色ID
                        itemJson.put("PS_C_CLR_ID", h.get("PS_C_SPEC1OBJ_ID"));
                        HashMap specobj = viewDLTranPlanMapper.selSpecobjData((Long) h.get("PS_C_SPEC1OBJ_ID"));

                        //颜色编码
                        itemJson.put("PS_C_CLR_ECODE", specobj.get("ECODE"));
                        //颜色名称
                        itemJson.put("PS_C_CLR_ENAME", specobj.get("ENAME"));
                    }

                    if (null != h.get("PS_C_SPEC2OBJ_ID")) {
                        //尺寸ID
                        itemJson.put("PS_C_SIZE_ID", h.get("PS_C_SPEC2OBJ_ID"));
                        HashMap specobj = viewDLTranPlanMapper.selSpecobjData((Long) h.get("PS_C_SPEC2OBJ_ID"));

                        //尺寸编码
                        itemJson.put("PS_C_SIZE_ECODE", specobj.get("ECODE"));
                        //尺寸名称
                        itemJson.put("PS_C_SIZE_ENAME", specobj.get("ENAME"));
                    }

                    //条码ID
                    itemJson.put("PS_C_SKU_ID", h.get("ID"));

                    if (null != h.get("PS_C_PRO_ID")) {
                        //商品ID
                        itemJson.put("PS_C_PRO_ID", h.get("PS_C_PRO_ID"));
                        HashMap proHashMap = viewDLTranPlanMapper.selProData((Long) h.get("PS_C_PRO_ID"));

                        if (null != proHashMap && proHashMap.size() > 0) {
                            //款号
                            itemJson.put("PS_C_PRO_ECODE", proHashMap.get("ECODE"));
                            //商品名称
                            itemJson.put("PS_C_PRO_ENAME", proHashMap.get("ENAME"));
                            //商品图片
                            itemJson.put("PS_C_PRO_IMAGE", proHashMap.get("IMAGE"));
                            //吊牌价
                            itemJson.put("PRICE_LIST", proHashMap.get("PRICELIST"));
                            //品类ID
                            itemJson.put("PRO_TYPE_DEPART_ID", proHashMap.get("NUMDIM26"));
                        } else {
                            throw new NDSException("商品档案 查询为空！  商品ID：" + h.get("PS_C_PRO_ID"));
                        }

                        if (itemJson.containsKey("PRO_TYPE_DEPART_ID") &&
                                (null != itemJson.getLong("PRO_TYPE_DEPART_ID"))) {
                            HashMap proDimHashMap = viewDLTranPlanMapper.
                                    selProItemData(itemJson.getLong("PRO_TYPE_DEPART_ID"));

                            if (null != proDimHashMap && proDimHashMap.size() > 0) {
                                //品类编码
                                itemJson.put("PRO_TYPE_DEPART_ECODE", proDimHashMap.get("ECODE"));
                                //品类名称
                                itemJson.put("PRO_TYPE_DEPART_ENAME", proDimHashMap.get("ENAME"));
                            } else {
                                throw new NDSException("商品属性 查询为空！  品类ID：" +
                                        itemJson.getLong("PRO_TYPE_DEPART_ID"));
                            }
                        }
                    }
                } else {
                    throw new NDSException("SKU 查询为空！  sku编码：" + skuEcode);
                }

                //销售区域
                String storeOrgEcode = itemJson.getString("CP_C_STOREORG_ID");
                if (null != storeOrgEcode) {
                    HashMap storeOrgHashMap = viewDLTranPlanMapper.
                            selStoreOrgData(storeOrgEcode);

                    if (null != storeOrgHashMap && storeOrgHashMap.size() > 0) {
                        itemJson.put("CP_C_STOREORG_ID", storeOrgHashMap.get("ID"));
                    } else {
                        itemJson.put("CP_C_STOREORG_ID", null);
                    }
                }
            }

            if (null != itemJson.getString("PS_C_PRO_ECODE")) {
                String ecode = itemJson.getString("PS_C_PRO_ECODE");
                if (!proEcodeList.contains(ecode)) {
                    proEcodeList.add(ecode);
                    ecodeList.append(ecode + ",");
                    enameList.append(itemJson.getString("PS_C_PRO_ENAME") + ",");
                }
            }

            if (itemJson.containsKey("PRICE_LIST")) {
                BigDecimal price = itemJson.getBigDecimal("PRICE_LIST");
                BigDecimal execPlan = price.multiply(itemJson.getBigDecimal("QTY_EXEC_PLAN"));
                //计划金额
                itemJson.put("AMT_EXEC_PLAN", execPlan);
            }

            if (null != itemJson.getLong("PRO_TYPE_DEPART_ID")) {
                Long departId = itemJson.getLong("PRO_TYPE_DEPART_ID");
                if (!departIdList.contains(departId)) {
                    departIdList.add(departId);
                    departIdBuffer.append(departId + ",");
                }
            }

            BigDecimal itemQtyExecPre = itemJson.getBigDecimal("QTY_EXEC_PLAN").
                    subtract(itemJson.getBigDecimal("QTY_EXEC"));
            if (itemQtyExecPre.compareTo(BigDecimal.ZERO) < 0) {
                itemQtyExecPre = BigDecimal.ZERO;
            }

            //未执行数量
            itemJson.put("QTY_EXEC_PRE", itemQtyExecPre);

            //出库数量
            itemJson.put("QTY_OUT", 0);
            if (itemJson.getBigDecimal("QTY_EXEC").compareTo(BigDecimal.ZERO) > 0) {
                //未执行门店数
                itemJson.put("QTY_STORE_EXEC_PRE", 0);
            } else {
                itemJson.put("QTY_STORE_EXEC_PRE", itemJson.getInteger("QTY_STORE"));
            }

            if (itemJson.containsKey("CP_C_DEST_ECODE")) {
                String storeEcode = itemJson.getString("CP_C_DEST_ECODE");
                HashMap storeHashMap = viewDLTranPlanMapper.
                        selStoreData(storeEcode);

                if (null != storeHashMap && storeHashMap.size() > 0) {
                    //店仓类型
                    itemJson.put("DEST_TYPE", storeHashMap.get("STORETYPE"));
                    //收货店仓ID
                    itemJson.put("CP_C_DEST_ID", storeHashMap.get("ID"));
                    if (null != storeHashMap.get("ID")) {
                        storeID = TypeUtils.castToLong(storeHashMap.get("ID"));
                    }
                } else {
                    throw new NDSException("店仓 查询为空！  店仓编码：" + storeEcode);
                }
            }

            qtyExecPlan = qtyExecPlan.add(itemJson.getBigDecimal("QTY_EXEC_PLAN"));
            amtExec = amtExec.add(itemJson.getBigDecimal("AMT_EXEC_PLAN"));
            qtyExec = qtyExec.add(itemJson.getBigDecimal("QTY_EXEC"));
            qtyExecPre = qtyExecPre.add(itemJson.getBigDecimal("QTY_EXEC_PRE"));
//            qtyStore += itemJson.getInteger("QTY_STORE");
//            if (0 == itemJson.getInteger("QTY_STORE_EXEC_PRE")) {
//                storeExecPre += itemJson.getInteger("QTY_STORE_EXEC_PRE");
//            }

            /******处理执行换店明细数据处理*******/
            JSONObject execItemJson = new JSONObject();

            //收货店铺ID
            execItemJson.put("StoreId", itemJson.get("CP_C_DEST_ID"));
            //收货店铺编码
            execItemJson.put("StoreCode", itemJson.get("CP_C_DEST_ECODE"));
            //收货店铺类型
            execItemJson.put("StoreType", itemJson.get("DEST_TYPE"));
            //门店数量
            execItemJson.put("QtyStore", itemJson.get("QTY_STORE"));
            //计划执行数量
            execItemJson.put("QtyExecPlan", itemJson.get("QTY_EXEC_PLAN"));
            //计划金额
            execItemJson.put("AmtExecPlan", itemJson.get("AMT_EXEC_PLAN"));
            //已执行数量
            execItemJson.put("QtyExec", itemJson.get("QTY_EXEC"));
            //未执行数量
            execItemJson.put("QtyExecPre", itemJson.get("QTY_EXEC_PRE"));
            //出库数量合计
            execItemJson.put("QtyOut", 0);
            //未执行门店数
            execItemJson.put("QtyStoreExecPre", itemJson.get("QTY_STORE_EXEC_PRE"));
            //款号
            execItemJson.put("ProEcode", itemJson.get("PS_C_PRO_ECODE"));
            //商品ID
            execItemJson.put("ProId", itemJson.get("PS_C_PRO_ID"));
            //商品名称
            execItemJson.put("ProEname", itemJson.get("PS_C_PRO_ENAME"));
            //商品图片
            execItemJson.put("ProImage", itemJson.get("PS_C_PRO_IMAGE"));
            //吊牌价
            execItemJson.put("TagPrice", itemJson.get("PRICE_LIST"));
            //颜色ID
            execItemJson.put("ClrId", itemJson.get("PS_C_CLR_ID"));
            //颜色编码
            execItemJson.put("ClrEcode", itemJson.get("PS_C_CLR_ECODE"));
            //颜色名称
            execItemJson.put("ClrEname", itemJson.get("PS_C_CLR_ENAME"));
            //尺寸ID
            execItemJson.put("SizeId", itemJson.get("PS_C_SIZE_ID"));
            //尺寸编码
            execItemJson.put("SizeEcode", itemJson.get("PS_C_SIZE_ECODE"));
            //尺寸名称
            execItemJson.put("SizeName", itemJson.get("PS_C_SIZE_ENAME"));
            //SKU编码
            execItemJson.put("SkuEcode", itemJson.get("PS_C_SKU_ECODE"));
            //条码ID
            execItemJson.put("SkuId", itemJson.get("PS_C_SKU_ID"));
            //品类ID
            execItemJson.put("ProTypeDepartId", itemJson.get("PRO_TYPE_DEPART_ID"));
            //品类编码
            execItemJson.put("ProTypeDepartEcode", itemJson.get("PRO_TYPE_DEPART_ECODE"));
            //品类名称
            execItemJson.put("ProTypeDepartEname", itemJson.get("PRO_TYPE_DEPART_ENAME"));
            //销售区域
            if (null != itemJson.getString("CP_C_STOREORG_ID")) {

                execItemJson.put("CP_C_STOREORG_ID", itemJson.get("CP_C_STOREORG_ID"));

            }
            tranPlanItemArray.add(execItemJson);

//            itemJson.remove("CP_C_DEST_ECODE");
        }
        if (ecodeList.length() > 0) {
            ecodeList.deleteCharAt(ecodeList.length() - 1);
        }
        if (enameList.length() > 0) {
            enameList.deleteCharAt(enameList.length() - 1);
        }
        if (departIdBuffer.length() > 0) {
            departIdBuffer.deleteCharAt(departIdBuffer.length() - 1);
        }

        /*************处理主表数据************/
        String billDate = zbJS.getString("OPR_DATE");
        int ExecuteStatus = zbJS.getIntValue("EXECUTESTATUS");

        JSONObject newzbJson = new JSONObject();
        Set<String> keySet = zbJS.keySet();
        for (String key : keySet) {
            if ("OPR_ECODE".equals(key) || "IDLIST".equals(key)
                    || "STATUS_TYPE".equals(key) || "TRAN_PLAN_ID".equals(key)
                    || "OPR_DATE".equals(key) || "EXECUTESTATUS".equals(key)) {
                continue;
            } else {
                newzbJson.put(key, zbJS.get(key));
            }
        }

        //单据模式
        newzbJson.put("BILL_MODEL", 1);
        //单据模式名称
        newzbJson.put("BILL_MODEL_ENAME", "多店");
        //单据来源
        newzbJson.put("BILL_SOURCE", 2);
        //单据来源名称
        newzbJson.put("BILL_SOURCE_ENAME", "缓冲接口传入数据");

        int orderType = zbJS.getIntValue("BILL_TYPE");

        if (orderType > 0) {
            String billTypeName = null;
            switch (orderType) {
                case 1:
                    billTypeName = "补货订单";
                    break;
                case 2:
                    billTypeName = "新品铺货";
                    break;
                case 3:
                    billTypeName = "新品试销";
                    break;
                case 4:
                    billTypeName = "特殊订单";
                    break;
                default:
                    billTypeName = null;
                    break;
            }
            newzbJson.put("BILL_TYPE_ENAME", billTypeName);
        }


        if (zbJS.containsKey("CP_C_ORIG_ECODE") && (null != zbJS.getString("CP_C_ORIG_ECODE"))) {
            String ecode = zbJS.getString("CP_C_ORIG_ECODE");
            HashMap storeHashMap = viewDLTranPlanMapper.selStoreData(ecode);

            if (null != storeHashMap && storeHashMap.size() > 0) {
                //发货店仓ID
                newzbJson.put("CP_C_ORIG_ID", storeHashMap.get("ID"));
            } else {
                throw new NDSException("店仓 查询为空   店仓编码:" + ecode);
            }
        }

        //明细款
        newzbJson.put("PS_C_PRO_ECODE_LIST", ecodeList);
        //明细款名称
        newzbJson.put("PS_C_PRO_ENAME_LIST", enameList);
        //计划执行数量合计
        newzbJson.put("SUM_QTY_EXEC_PLAN", qtyExecPlan);
        //调拨金额合计
        newzbJson.put("SUM_AMT_EXEC_PLAN", amtExec);
        //已执行数量合计
        newzbJson.put("SUM_QTY_EXEC", qtyExec);
        //未执行数量合计
        newzbJson.put("SUM_QTY_EXEC_PRE", qtyExecPre);
        //出库数量合计
        newzbJson.put("SUM_QTY_OUT", 0);
//        //门店数量
//        newzbJson.put("SUM_QTY_STORE", qtyStore);
//        //未执行门店数
//        newzbJson.put("SUM_QTY_STORE_EXEC_PRE", storeExecPre);
        //是否缓冲补货生成
        newzbJson.put("IS_BF_SUPPLY", "Y");
        //收货店仓ID
//        newzbJson.put("CP_C_DEST_ID", storeID);
        newzbJson.remove("CP_C_DEST_ECODE");

        JSONObject fixColumn = new JSONObject();
        fixColumn.put("DL_B_TRAN_PLAN", newzbJson);
        fixColumn.put("DL_B_TRAN_PLAN_ITEM", itemJS);

        JSONObject resultJson = new JSONObject();
        resultJson.put("objid", -1);
        resultJson.put("fixcolumn", fixColumn);
        resultJson.put("table", "DL_B_TRAN_PLAN");

        /******调拨计划单执行换店参数*******/
//        Integer executestatus;
//        if (qtyExec.compareTo(BigDecimal.ZERO) > 0) {
//            executestatus = 2;
//        } else {
//            executestatus = 1;
//        }
        JSONObject execJson = new JSONObject();
        execJson.put("BillDate", newzbJson.getLong("BILL_DATE"));
        //发货仓ID
        execJson.put("OrigId", newzbJson.getLong("CP_C_ORIG_ID"));
        execJson.put("BillNo", newzbJson.getString("BILL_NO"));
        //计划执行数量合计
        execJson.put("SumQtyExecPlan", qtyExecPlan);
        //计划金额合计
        execJson.put("SumAmtExecPlan", amtExec);
        //未执行数量合计
        execJson.put("SumQtyExecPre", qtyExecPre);
        //已执行数量合计
        execJson.put("SumQtyExec", qtyExec);
        //明细款号合集
        execJson.put("EcodeList", ecodeList);
        //明细款名字合集
        execJson.put("ENameList", enameList);
        //品类id合集
        execJson.put("DepartIdList", departIdBuffer);
        //执行状态
        execJson.put("ExecuteStatus", ExecuteStatus + 1);
        //操作用户ID
        execJson.put("ExecutorId", user.getId());
        //操作用户登录名
        execJson.put("ExecutorEname", user.getEname());
        //操作用户姓名
        execJson.put("ExecutorName", user.getName());
        //操作时间
        execJson.put("ExecutorDate", billDate);
        execJson.put("SumQtyStore", zbJS.get("SUM_QTY_STORE"));
        execJson.put("SumQtyStoreExecPre", zbJS.get("SUM_QTY_STORE_EXEC_PRE"));

        execJson.put("TranPlanItemList", tranPlanItemArray);


        if ("BILL_RATION_EXEC".equals(statusType) || "BILL_RATION_CHANGE".equals(statusType)) {
            return execJson;
        } else {
            return resultJson;
        }
    }


    /**
     * ES查询
     *
     * @param billNo 单据编号
     * @return id
     */
    public JSONObject es(String billNo) {
        JSONObject bill_no = esUtil.generateMatch("BILL_NO", billNo);
        List<JSONObject> terms = esUtil.packageTerm(bill_no);
        JSONObject jsonObject = null;
        try {
            jsonObject = esUtil.searchAllDataByTerms(btranEsName.getIndex(),
                    btranEsName.getPlantype(), "1", "10000", terms);
            log.debug("es_jsonObject->" + jsonObject);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return jsonObject;
    }

    private JSONObject billdata(JSONObject esData) {
        JSONObject hits = esData.getJSONObject("hits");
        JSONArray hitsArray = hits.getJSONArray("hits");
        JSONObject sourceJson = hitsArray.getJSONObject(0);

        JSONObject source = sourceJson.getJSONObject("_source");

        return source;
    }

}
